<?php
namespace Alidayu;

class Alidayu{
	public $ak = '23623727';
	public $sk = '0a9ecb1f5e363fbb715b80d3d2526992';
	public $method = 'alibaba.aliqin.fc.sms.num.send';
	public $version = '2.0';
	public $signType = 'md5';
	public $signature = '智慧名片';
	public $url = 'http://gw.api.taobao.com/router/rest';
	/**
	 * [createSign 签名函数]
	 * @param  Array  $paramArr [参数数组]
     * @param  String $secret   [secret]
     * @return String           [返回签名]
    */
	static function createSign ($paramArr, $secret) {
		$sign = $secret;
		ksort($paramArr);
		foreach ($paramArr as $key => $val) {
			if ($key != '' && $val != '') {
			  $sign .= $key.$val;
			}
		}
		$sign.=$secret;
		$sign = strtoupper(md5($sign));
		return $sign;
	}
	
	/**
	 * [createStrParam 组参函数]
	 * @param  Array $paramArr [参数数组]
	 * @return String          [返回Url]
	 */
	static function createStrParam ($paramArr) {
		$strParam = '';
		foreach ($paramArr as $key => $val) {
			if ($key != '' && $val != '') {
			   $strParam .= $key.'='.urlencode($val).'&';
			}
		}
		return $strParam;
	}
	
	/**
	 * [sendSms 发送短信]
	 * @param String $phone    [手机号码]
	 * @param String $tplcode  [短信模板ID]
	 * @param String $param    [短信模板变量]  {"key1":"value1","key2":"value2"}
	 * @return [type]          [description]
	 */
	public function sendSms ($phone,$tplcode,$param){
		$paramArr = array(
			'app_key' => $this->ak,
			'session_key' => '',
			'method' => $this->method,
			'format' => 'json',
			'v' => $this->version,
			'sign_method'=> $this->signType,
			'timestamp' => date('Y-m-d H:i:s'),
			//'fields' => 'nick,type,user_id',
			'sms_type' => 'normal',
			'sms_free_sign_name' => $this->signature,
			'sms_param' => $param,
			'rec_num' => $phone,
			'sms_template_code' => $tplcode
		);
		$sign = self::createSign($paramArr,$this->sk);
		$strParam = self::createStrParam($paramArr);
		$strParam .= 'sign='.$sign;
		$url = $this->url . '?' .$strParam;
		$result = file_get_contents($url);
		$arr = json_decode($result, true);
		return $arr['alibaba_aliqin_fc_sms_num_send_response']['result']['err_code'];
	}
}